#!/usr/bin/env python3
# coding:utf-8

import paho.mqtt.client as mqtt

# MQTT Broker地址和端口
MQTT_BROKER = 'localhost'
MQTT_PORT = 1883

# 请求主题和响应主题
REQUEST_TOPIC = 'request/topic'
RESPONSE_TOPIC = 'response/topic'

# 创建MQTT客户端实例
client = mqtt.Client()

# 定义消息回调函数
def on_message(client, userdata, message):
    print(f"Received request: '{str(message.payload.decode('utf-8'))}' on topic '{message.topic}'")
    # 发送响应消息
    response_message = "Hello, this is a response"
    client.publish(RESPONSE_TOPIC, response_message)
    print(f"Sent response: '{response_message}' to topic '{RESPONSE_TOPIC}'")

# 设置消息回调函数
client.on_message = on_message

# 连接到MQTT Broker
client.connect(MQTT_BROKER, MQTT_PORT, 60)

# 订阅请求主题
client.subscribe(REQUEST_TOPIC)

# 启动网络循环
client.loop_forever()